/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package BackingBeans;

import Facebook.FacebookClientLocal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.http.HttpServletRequest;
import smartgrid.Annotation;
import smartgrid.AnnotationInterface;
import smartgrid.Contract;
import smartgrid.Contracts;
import smartgrid.FacebookAccountInterface;
import smartgrid.exceptions.ContractNotExistsException;
import smartgrid.exceptions.FacebookAccountDisabledException;

/**
 *
 * @author claudio
 */
@ManagedBean
@SessionScoped
public class MarcadoresBackingBean {

    private Map<String, Contract> Contracts;
    private String SelectedContract;
    private String UserName;
    private String UserUID;
    private String NomeNovo;
    private String Descricao;
    private Map<String, Annotation> annotations;
    private String selectedAnnotation;
    private String hoje;

    /** Creates a new instance of MarcadoresBackingBean */
    public MarcadoresBackingBean() {
        this.Contracts = new HashMap<String, Contract>();
        this.annotations = new HashMap<String, Annotation>();
        Descricao = "";

        InitialContext initCtx;

        try {
            initCtx = new InitialContext();
            Contracts si = (Contracts) initCtx.lookup("java:global/SmartGridEA/ContractsManager");

            FacebookAccountInterface fm = (FacebookAccountInterface) initCtx.lookup("java:global/SmartGridEA/FacebookAccountManager");

            HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
            FacebookClientLocal fbl = null;
            if (request != null) {
                fbl = (FacebookClientLocal) request.getSession(true).getAttribute("facebook");
                if (fbl != null) {
                    this.UserName = fbl.getNome();
                    this.UserUID = fbl.getUId();
                }
            }

            List<Contract> ss = si.getContracts(fm.getFacebookAccountByUID(fbl.getUId()));
            if (ss != null) {
                System.out.println("NOT NULL");
                for (Contract s : ss) {
                    this.Contracts.put(s.getNumber(), s);
                }
                if(!ss.isEmpty())
                    this.setSelectedContract(ss.get(0).getNumber());
            }

//            AnnotationInterface ai = (AnnotationInterface) initCtx.lookup("java:global/SmartGridEA/AnnotationManager");
//            List<Annotation> as = ai.getContractFacebookAccountAnnotations(this.UserName, this.SelectedContract);
//            if (ss != null) {
//                for (Annotation a : as) {
//                    this.annotations.put(a.getName(), a);
//                }
//                this.selectedAnnotation = as.get(0).getName();
//            }


        } catch (FacebookAccountDisabledException ex) {
            Logger.getLogger(ContaBackingBean.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NamingException ex) {
            Logger.getLogger(UnregisteredBackingBean.class.getName()).log(Level.SEVERE, null, ex);
//        } catch (ContractNotExistsException ex) {
//            Logger.getLogger(MarcadoresBackingBean.class.getName()).log(Level.SEVERE, null, ex);
//
//        }
        }
    }

    public String getNomeNovo() {
        return NomeNovo;
    }

    public void setNomeNovo(String NomeNovo) {
        this.NomeNovo = NomeNovo;
    }

    
    
    public Set<String> getContractList() {
        return Contracts.keySet();
    }

    public String getHoje() {
        GregorianCalendar g = new GregorianCalendar();
        int dia = g.get(Calendar.DAY_OF_MONTH);
        int mes = g.get(Calendar.MONTH) + 1;
        int ano = g.get(Calendar.YEAR);
        return dia + "/" + mes + "/" + ano;
    }

    public Set<String> getAnnotationList() {
        return annotations.keySet();
    }

    public void setContracts(Map<String, Contract> Contracts) {
        this.Contracts = Contracts;
    }

    public String getSelectedContract() {
        return SelectedContract;
    }

    public void setSelectedContract(String SelectedContract) {
        try {
            InitialContext initCtx = new InitialContext();
            AnnotationInterface am = (AnnotationInterface) initCtx.lookup("java:global/SmartGridEA/AnnotationManager");
            List<Annotation> ans = am.getContractFacebookAccountAnnotations(this.UserUID, SelectedContract);
            
            this.annotations = new HashMap<String, Annotation>();
            for(Annotation an : ans ){
                this.annotations.put(an.getName(), an);
            }
            
            if(!ans.isEmpty())
                this.selectedAnnotation = ans.get(0).getName();
            
            this.SelectedContract = SelectedContract;
        } catch (FacebookAccountDisabledException ex) {
            Logger.getLogger(MarcadoresBackingBean.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ContractNotExistsException ex) {
            Logger.getLogger(MarcadoresBackingBean.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NamingException ex) {
            Logger.getLogger(MarcadoresBackingBean.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public String getUserName() {
        return UserName;
    }

    public void setUserName(String UserName) {
        this.UserName = UserName;
    }

    public String getSelectedAnnotation() {
        return selectedAnnotation;
    }

    public void setSelectedAnnotation(String selectedAnnotation) {
        this.selectedAnnotation = selectedAnnotation;
    }

    public String getData() {
        if (selectedAnnotation == null) {
            return "";
        }
        Annotation a = this.annotations.get(this.selectedAnnotation);
        if (a != null) {
            return a.getDate().toString();
        }
        return "";
    }

    public void setData(String Data) {
    }

    public Map<String, Annotation> getAnnotations() {
        return annotations;
    }

    public void setAnnotations(Map<String, Annotation> annotations) {
        this.annotations = annotations;
    }

    public String getDescricao() {
        if (selectedAnnotation == null) {
            return "";
        }
        Annotation a = this.annotations.get(this.selectedAnnotation);
        if (a != null) {
            return a.getName();
        }
        return "";
    }

    public void setDescricao(String Descricao) {
        this.Descricao = Descricao;
    }

    public void setHoje(String hoje) {
        this.hoje = hoje;
    }

    private boolean validateEmpty() {
        boolean ret = true;
        FacesContext ctx = FacesContext.getCurrentInstance();

        if (this.hoje == null || this.hoje.isEmpty()) {
            FacesMessage msg = new FacesMessage();
            msg.setSeverity(FacesMessage.SEVERITY_WARN);
            msg.setSummary("Deve seleccionar um dia para guardar o marcador");
            msg.setDetail("Deve seleccionar um dia para guardar o marcador");
            ctx.addMessage("contractform:descricao", msg);
            ret = false;
        }

        if (this.NomeNovo == null || this.NomeNovo.isEmpty()) {
            FacesMessage msg = new FacesMessage();
            msg.setSeverity(FacesMessage.SEVERITY_WARN);
            msg.setSummary("Deve preencher algo que identifique este marcador.");
            msg.setDetail("Deve preencher algo que identifique este marcador.");
            ctx.addMessage("contractform:descricao", msg);
            ret = false;
        }
        return ret;
    }

    public String submit() {
        FacesContext ctx = FacesContext.getCurrentInstance();
        if (!this.validateEmpty()) {
            return "";
        } else {
            HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
            FacebookClientLocal fbl = (FacebookClientLocal) request.getSession(true).getAttribute("facebook");
            if (fbl == null) {
                return "error";
            }
            try {
                InitialContext initCtx = new InitialContext();
                FacebookAccountInterface fb = (FacebookAccountInterface) initCtx.lookup("java:global/SmartGridEA/FacebookAccountManager");
                Contracts cm = (Contracts) initCtx.lookup("java:global/SmartGridEA/ContractsManager");
                AnnotationInterface ai = (AnnotationInterface) initCtx.lookup("java:global/SmartGridEA/AnnotationManager");

                char[] cArray = hoje.toCharArray();
                String dia = new String(cArray, 0, 2);
                String mes = new String(cArray, 3, 2);
                String ano = new String(cArray, 6, 4);

                ai.insertAnnotation(this.UserUID, this.SelectedContract, this.NomeNovo, new GregorianCalendar(new Integer(ano), (new Integer(mes) - 1), new Integer(dia)));

            } catch (FacebookAccountDisabledException ex) {
                FacesMessage msg = new FacesMessage();
                msg.setSeverity(FacesMessage.SEVERITY_WARN);
                msg.setSummary("Esta conta do Facebook está desactivada");
                msg.setDetail("Esta conta do Facebook está desactivada");
                ctx.addMessage("contractform:supplierCombo", msg);
                return "";
            } catch (ContractNotExistsException ex) {
                FacesMessage msg = new FacesMessage();
                msg.setSeverity(FacesMessage.SEVERITY_WARN);
                msg.setSummary("O Contrato já não está associado à sua conta");
                msg.setDetail("O Contrato já não está associado à sua conta");
                ctx.addMessage("contractform:supplierCombo", msg);
                return "";

            } catch (NamingException ex) {
                Logger.getLogger(MarcadoresBackingBean.class.getName()).log(Level.SEVERE, null, ex);
                return "error";
            }

            return "";
        }
    }
}
